package cn.tedu.charging.order.mqtt;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class MqttTemplate<T> {
    @Autowired
    private MqttClient mqttClient;
    /**
     * 可以根据自己的需求封装不同的场景生产发送的代码
     */
    //发送消息 不一定什么类型T 保存 qos级别是1
    public boolean sendDefault(String destination,T message){
        try{
            mqttClient.publish(destination,serializer(message),1,true);
            return true;
        }catch (Exception e){
            log.error("发送失败",e);
            return false;
        }
    }
    //发送消息 类型T 不保存 qos级别1
    public boolean sendWithoutRetain(String destination,T message){
        try{
            mqttClient.publish(destination,serializer(message),1,false);
            return true;
        }catch (Exception e){
            log.error("发送失败",e);
            return false;
        }
    }
    //序列化 对象转化json json转化byte[]
    private byte[] serializer(T message){
        String json=JSON.toJSONString(message);
        return json.getBytes(StandardCharsets.UTF_8);
    }
}
